<?php

namespace IMT\AccountBundle\Controller;

use IMT\UserBundle\Entity\Contact;

use IMT\UserBundle\Controller\ContactController;

use IMT\Plugins\ParticipantsBundle\Controller\DefaultController as PluginParticipant;

use IMT\AccountBundle\Entity\Account;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use IMT\AccountBundle\Entity\AccountGmail;
use IMT\AccountBundle\Form\AccountGmailType;

/**
 * AccountGmail controller.
 *
 */
class AccountGmailController extends Controller
{
    /**
     * Lists all AccountGmail entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('IMTAccountBundle:AccountGmail')->findAll();

        return $this->render('IMTAccountBundle:AccountGmail:index.html.twig', array(
            'entities' => $entities
        ));
    }

    /**
     * Finds and displays a AccountGmail entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->get('security.context')->getToken()->getUser();

        $entity = $em->getRepository('IMTAccountBundle:AccountGmail')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AccountGmail entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('IMTAccountBundle:AccountGmail:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        	'contacts' => ContactController::getContactList($entity->getContacts(), $user)
        ));
    }

    /**
     * Displays a form to create a new AccountGmail entity.
     *
     */
    public function newAction()
    {
        $entity = new AccountGmail();
        $form   = $this->createForm(new AccountGmailType(), $entity);
        
        $user = $this->get('security.context')->getToken()->getUser();

        return $this->render('IMTAccountBundle:AccountGmail:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        	'contacts' => ContactController::getContactList($entity->getContacts(), $user)
        ));
    }

    /**
     * Creates a new AccountGmail entity.
     *
     */
    public function createAction()
    {
    	$user = $this->get('security.context')->getToken()->getUser();
    	
        $entity  = new AccountGmail();
        $entity->setUser($user);
        
        $request = $this->getRequest();
        $form    = $this->createForm(new AccountGmailType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            
            $contact = new Contact();
            $contact->setEmail($user->getEmail());
            $contact->setUser($user);
            $contact->setName($user->getProfil()->getName());
            $contact->setFirstname($user->getProfil()->getFirstname());
            
            $entity->addContact($contact);
            
            $em->persist($entity);
            $em->flush();
            
       	 	if($entity->getActiveSynch() && (!$entity->getAccessToken() || !$entity->getRefreshToken())){
        		$this->get('session')->set('imt_account_synch_id', $entity->getId());
        		return $this->forward('IMTSynchBundle:Connect:redirectToService', array('service' => 'googlecontact'));
        	}
            
            return $this->redirect($this->generateUrl('account_home'));
            
        }

        return $this->render('IMTAccountBundle:AccountGmail:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        	'contacts' => ContactController::getContactList($entity->getContacts(), $user)
        ));
    }

    /**
     * Displays a form to edit an existing AccountGmail entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->get('security.context')->getToken()->getUser();

        $entity = $em->getRepository('IMTAccountBundle:AccountGmail')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AccountGmail entity.');
        }

        $editForm = $this->createForm(new AccountGmailType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('IMTAccountBundle:AccountGmail:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        	'contacts' => ContactController::getContactList($entity->getContacts(), $user)
        ));
    }

    /**
     * Edits an existing AccountGmail entity.
     *
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->get('security.context')->getToken()->getUser();

        $entity = $em->getRepository('IMTAccountBundle:AccountGmail')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AccountGmail entity.');
        }

        $editForm   = $this->createForm(new AccountGmailType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);
        
        $validator = $this->get('validator');

        if ($editForm->isValid()) {        	
            $em->persist($entity);
            $em->flush();
        	
        	if($entity->getActiveSynch() && (!$entity->getAccessToken() || !$entity->getRefreshToken())){
        		$this->get('session')->set('imt_account_synch_id', $entity->getId());
        		return $this->forward('IMTSynchBundle:Connect:redirectToService', array('service' => 'googlecontact'));
        	}
        	
            return $this->redirect($this->generateUrl('account_home'));
        }

        return $this->render('IMTAccountBundle:AccountGmail:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        	'contacts' => ContactController::getContactList($entity->getContacts(), $user)
        ));
    }

    /**
     * Deletes a AccountGmail entity.
     *
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('IMTAccountBundle:AccountGmail')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find AccountGmail entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('account_home'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    
    public static function orderAllParticipants($participants)
    {
    	$indexs = array(
    			'#' => array('title' =>'#', 'values' => array()),
    			'a' => array('title' =>'A', 'values' => array()),
    			'b' => array('title' =>'B', 'values' => array()),
    			'c' => array('title' =>'C', 'values' => array()),
    			'd' => array('title' =>'D', 'values' => array()),
    			'e' => array('title' =>'E', 'values' => array()),
    			'f' => array('title' =>'F', 'values' => array()),
    			'g' => array('title' =>'G', 'values' => array()),
    			'h' => array('title' =>'H', 'values' => array()),
    			'i' => array('title' =>'I', 'values' => array()),
    			'j' => array('title' =>'J', 'values' => array()),
    			'k' => array('title' =>'K', 'values' => array()),
    			'l' => array('title' =>'L', 'values' => array()),
    			'm' => array('title' =>'M', 'values' => array()),
    			'n' => array('title' =>'N', 'values' => array()),
    			'o' => array('title' =>'O', 'values' => array()),
    			'p' => array('title' =>'P', 'values' => array()),
    			'q' => array('title' =>'Q', 'values' => array()),
    			'r' => array('title' =>'R', 'values' => array()),
    			's' => array('title' =>'S', 'values' => array()),
    			't' => array('title' =>'T', 'values' => array()),
    			'u' => array('title' =>'U', 'values' => array()),
    			'v' => array('title' =>'V', 'values' => array()),
    			'w' => array('title' =>'W', 'values' => array()),
    			'x' => array('title' =>'X', 'values' => array()),
    			'y' => array('title' =>'Y', 'values' => array()),
    			'z' => array('title' =>'Z', 'values' => array()),
    	);
    	 
    	foreach($participants as $participant){
    		$index = strtolower(substr(trim($participant->getFirstname()), 0, 1));
    		$indexs[(isset($indexs[$index])) ? $index : '#']['values'][] = $participant;
    	}
    	 
    	foreach($indexs as $name => $index){
    		if(sizeof($index['values']) == 0) unset($indexs[$name]);
    	}
    	 
    	return $indexs;
    }
}
